﻿using AduSkin.Controls.Metro;
using DBMC_Core;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DBMC
{
    /// <summary>
    /// Update.xaml 的交互逻辑
    /// </summary>
    public partial class Update : Window
    {
        private bool isDragging;
        private Point startPoint;
        // 声明为类的静态字段
        private static readonly HttpClient client = new HttpClient();
        private CancellationTokenSource cts;

        public Update()
        {
            InitializeComponent();
            Loaded += delegate { LauncherCore.WriteLog($"启动器核心：检查更新 - 窗口打开正常"); };
            GetUpdate();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            if (cts != null)
            {
                cts.Cancel();
            }
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            startPoint = e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPoint = e.GetPosition(this);
                this.Left += currentPoint.X - startPoint.X;
                this.Top += currentPoint.Y - startPoint.Y;
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private async void GetUpdate()
        {
            await Task.Delay(1000);
            RestClient client = new RestClient("https://api.dbhg.top/api/dbmc/update");
            RestRequest request = new RestRequest
            {
                Method = Method.Post,
                Timeout = 30000
            };
            request.AddHeader("Host", "api.dbhg.top");
            RestResponse response = client.Execute(request);
            if (response.IsSuccessful)
            {
                LauncherCore.WriteLog($"启动器核心：检查更新 - 请求服务器成功");
                dynamic Response = JsonConvert.DeserializeObject(response.Content);
                if ((bool)Response.update == false)
                {
                    LauncherCore.WriteLog($"启动器核心：检查更新 - 服务器未开启更新");
                    UpdateTips.Text = "现在是最新的啦OVO！";
                    UpdateProgressBar.ProgressBarState = ProgressBarState.None;
                    await Task.Delay(2000);
                    Close();
                }
                else
                {
                    if (IsUpdateRequired((string)Response.version) == false)
                    {
                        LauncherCore.WriteLog($"启动器核心：检查更新 - 当前版本为最新的");
                        UpdateTips.Text = "现在是最新的啦OVO！";
                        UpdateProgressBar.ProgressBarState = ProgressBarState.None;
                        await Task.Delay(2000);
                        Close();
                    }
                    else
                    {
                        if ((string)Response.url == "")
                        {
                            LauncherCore.WriteLog($"启动器核心：检查更新 - 更新链接为空");
                            UpdateTips.Text = "现在是最新的啦OVO！";
                            UpdateProgressBar.ProgressBarState = ProgressBarState.None;
                            await Task.Delay(2000);
                            Close();
                        }
                        else
                        {
                            LauncherCore.WriteLog($"启动器核心：检查更新 - 已检测到最新版本");
                            UpdateTips.Text = "有新版本了OVO！";
                            UpdateProgressBar.ProgressBarState = ProgressBarState.None;
                            MessageBoxResult messageBoxResult = AduMessageBox.Show("是否现在更新？", "有新版本了OVO！", MessageBoxButton.YesNo);
                            if (messageBoxResult == MessageBoxResult.Yes)
                            {
                                LauncherCore.WriteLog($"启动器核心：检查更新 - 用户选择更新，获取下载链接中...");
                                UpdateTips.Text = "获取下载链接中...";
                                // 创建新的 CancellationTokenSource
                                cts = new CancellationTokenSource();
                                CancellationToken token = cts.Token;

                                string fileUrl = Response.url;
                                string temporaryFolderPath = System.IO.Path.GetTempPath();

                                string localFilePath = System.IO.Path.Combine(temporaryFolderPath, "DBMC_Update.exe");

                                // 初始化Progress<T>来报告进度值
                                Progress<double> progressIndicator = new Progress<double>(ReportProgress);

                                try
                                {
                                    await DownloadFileAsync(fileUrl, localFilePath, progressIndicator, token);
                                    UpdateTips.Text = "下载完成";
                                    LauncherCore.WriteLog($"启动器核心：检查更新 - 下载完成，更新包位置在：{localFilePath}，即将关闭程序，唤起更新包中...");
                                    Process.Start(localFilePath);
                                    Application.Current.Shutdown();
                                }
                                catch (Exception)
                                {
                                    UpdateTips.Text = "下载失败";
                                    LauncherCore.WriteLog($"启动器核心：检查更新 - 下载失败");
                                    await Task.Delay(2000);
                                    Close();
                                }
                            }
                            else
                            {
                                LauncherCore.WriteLog($"启动器核心：检查更新 - 用户选择不更新");
                                Close();
                            }
                        }

                    }

                }
            }
        }

        public async Task DownloadFileAsync(string requestUri, string outputPath, IProgress<double> progress, CancellationToken cancellationToken)
        {
            using (HttpResponseMessage response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
            {
                response.EnsureSuccessStatusCode();
                long? contentLength = response.Content.Headers.ContentLength;

                using (Stream stream = await response.Content.ReadAsStreamAsync())
                using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    long totalRead = 0L;
                    byte[] buffer = new byte[8192];
                    bool isMoreToRead = true;

                    do
                    {
                        int read = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
                        if (read == 0)
                        {
                            isMoreToRead = false;
                        }
                        else
                        {
                            await fileStream.WriteAsync(buffer, 0, read, cancellationToken);

                            totalRead += read;
                            if (contentLength.HasValue)
                            {
                                double progressValue = (double)totalRead / contentLength.Value;
                                progress.Report(progressValue);
                            }
                        }
                    }
                    while (isMoreToRead);
                }
            }
        }

        public void ReportProgress(double value)
        {
            UpdateProgressBar.Value = value * 100;
            UpdateTips.Text = $"下载中 {value:P2}";
        }

        private bool IsUpdateRequired(string specifiedVersionString)
        {
            try
            {
                Version specifiedVersion = new Version(specifiedVersionString);
                Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version;

                return currentVersion.CompareTo(specifiedVersion) < 0;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("The specified version string is not a valid version format. " + ex.Message);
                return false;
            }
            catch (Exception ex)
            {
                // 处理其他潜在异常
                Console.WriteLine("An unexpected error occurred: " + ex.Message);
                return false;
            }
        }
    }
}
